/**
 * 
 */
package com.uw.tookit;

import java.util.HashMap;
import java.util.Map;

/**
 * @author muelnet
 *
 */
public class InformationFactory {
	
	// Reference to the only copy of this class, in case it's needed
	private static InformationFactory reference;
    
    // These are the indices of the different objects in the String array
    // created from splitting the information provided by the server.
    private static final int BUSINESS_ID = 1;
    private static final int NAME = 0;
    private static final int LATITUDE = 2;
    private static final int LONGITUDE = 3;
    private static final int ADDRESS=4;
    private static final int HOURS = 7;
    private static final int CATEGORY = 5;
    private static final int DESCRIPTION = 6;
	
	/**
	 * Keep people from instantiating InformationFactory
	 * as I only need it as a singleton
	 */
	private InformationFactory() {
		//This is blank on purpose.
	}
	
	/**
	 * Allow for a reference to the factory. Makes sure there is only one
	 * version of the Information by being synchronized and only creating
	 * one if one does not exist
	 * @return returns a reference to the only information factory
	 */
	public static synchronized InformationFactory getInformationFactory() {
		if(reference == null)
			reference = new InformationFactory();
		
		return reference;
	}
	
	/**
	 * Returns a class which contains all the data required to populate
	 * the InformationActivity page.
	 * 
	 * @return A class holding all the relevant information about a location
	 */
	public static InformationPageData getLocationData(int businessID) {
		
		return parseServerData(getServerData(businessID), 
				getServerRating(businessID));
	}
	/**
	 * Given a businessID returns a String of data from the server.
	 * @param businessID the ID for the location to lookup its information
	 * @return the string returned by the server for the given business id
	 */
	private static String getServerData(int businessID) {
        // Setup the query
		Map<String, String> params = new HashMap<String, String>();
		params.put("bid", "" + businessID);
        // removes extraneous commas
		return ServerCommunicator.executeHttpRequest("search.php", 
				params );
        
	}
	
	/**
	 * Sends a request to the server to get the rating for a specific business
	 * @param businessID The businessID of the location you want to look up.
	 * @return The ratings string returned from the server
	 */
	private static String getServerRating(int businessID) {
		// Setup the parameters
		Map<String, String> params = new HashMap<String, String>();
		params.put("bid", "" + businessID);
		params.put("rating", "get");
		// Send the request to the server and return it
		return ServerCommunicator.executeHttpRequest("search.php", params);
	}
	
	/**
     * Parses the data sent back by the server and then returns an
     * @return InformationPageData containing the information from the server
     */
	private static InformationPageData parseServerData(String serverData, 
			String ratings) {
		// Check for network connection problems, or improper businessID
		if (serverData == null || serverData.equals(""))
			return null;
        // Parse the Data
		serverData = serverData.substring(1, serverData.length() - 1);
		String[] fieldsList = serverData.split("~");
		
		// Create the description text	
		String longDescription = "";
		
		// If the address is unknown don't display it.
		if(!fieldsList[ADDRESS].equals("??")) {
			longDescription = "A D D R E S S:\n" + 
					fieldsList[ADDRESS] + "\n\n";
		}
		
		// If the location doesn't have hours, don't display them
		longDescription = fieldsList.length == 8 ? 
				longDescription + "H O U R S:\n" + fieldsList[HOURS] +"\n\n" : 
				longDescription;
		// All the descriptive tags assigned to this location
		longDescription = longDescription + "T A G S:\n" + 
				fieldsList[DESCRIPTION];
		
		// Set up ratings, both good and bad are set to -1 if the location 
		// doesn't allow ratings
		int good = -1;
		int bad = -1;
		if (ratings != null && !ratings.equals("")) {
			// Parse the rating
			ratings = ratings.substring(1, ratings.length() - 1);
			String[] ratingsList = ratings.split("~");
			good = Integer.parseInt(ratingsList[0]);
			bad = Integer.parseInt(ratingsList[1]);
		}
		
        // Create a new instance of Information page data with the information
		// parsed from the server text.
		return new InformationPageData(
            Integer.parseInt(fieldsList[BUSINESS_ID]),
            fieldsList[NAME], 
            longDescription, 
            chooseIcon(fieldsList[CATEGORY]), fieldsList[CATEGORY],
			Double.parseDouble(fieldsList[LATITUDE]), 
            Double.parseDouble(fieldsList[LONGITUDE]), 
            good, bad );
	}
	
	private static int chooseIcon(String category){
	    String[] mTextIds = {
    		"Building", "Dining", "Cafe", "Parking", "Bus", "ATM", 
    		"First Aid", "Computer Labs", "Power", "Library"
	    };
	    int[] mThumbIds = {
	    		R.drawable.building,
	            R.drawable.dining, R.drawable.cafe,
	            R.drawable.parking, R.drawable.bus,
	            R.drawable.atm, R.drawable.first_aid,
	            R.drawable.computer, R.drawable.power,
	            R.drawable.library
	    };
	    for(int i = 0; i < mTextIds.length; ++i) {
	    	if(category.equals(mTextIds[i]))
	    		return mThumbIds[i];
	    }
	    
		return R.drawable.building;
	}
	
	/**
	 * No Cloning allowed. This is a singleton
	 */
	@Override
	protected Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
	}
}
